package com.jiangnan.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.jiangnan.entity.LoginInfo
import com.jiangnan.entity.Res
import com.jiangnan.repository.AuthRepository
import com.jiangnan.repository.UserRepository
import com.jiangnan.util.EventUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class AuthViewModel(application: Application) : AndroidViewModel(application) {

    private val authRepository = AuthRepository()
    private var repository = UserRepository()

    // LiveData 保存发送验证码接口的返回信息
    private val _smsResponse = MutableLiveData<Res<Any>>()
    val smsResponse: LiveData<Res<Any>> = _smsResponse

    // LiveData 保存注册接口的返回信息
    private val _registerResponse = MutableLiveData<Res<Any>>()
    val registerResponse: LiveData<Res<Any>> = _registerResponse

    // LiveData 保存短信按钮倒计时秒数
    private val _countdown = MutableLiveData<Int>()
    val countdown: LiveData<Int> = _countdown

    // 登录请求返回结果 LiveData
    private val _loginResponse = MutableLiveData<Res<LoginInfo>>()
    val loginResponse: LiveData<Res<LoginInfo>> = _loginResponse

    // LiveData 保存重置密码接口返回结果
    private val _resetResponse = MutableLiveData<Res<Any>>()
    val resetResponse: LiveData<Res<Any>> = _resetResponse

    private var _toastMessage  = MutableLiveData<EventUtil<String>>()
    val toastMessage : LiveData<EventUtil<String>> = _toastMessage

    // 新增头像 URL LiveData
    private val _avatarUrl = MutableLiveData<String>()
    val avatarUrl: LiveData<String> get() = _avatarUrl




    /**
     * 调用发送验证码接口
     */
    fun sendSmsCode(phone: String) {
        viewModelScope.launch {
            try {
                val res = authRepository.sendSmsCode(phone)
                _smsResponse.value = res
                // 如果发送成功（code==1），启动倒计时
                if (res.code == 1) {
                    startCountdown(60)
                    _toastMessage.postValue(EventUtil("验证码发送成功"))
                }else{
                    _toastMessage.postValue(EventUtil("验证码发送失败\n请检查手机号是否正确"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _toastMessage.postValue(EventUtil("网络错误"))
            }
        }
    }

    /**
     * 调用注册接口
     */
    fun registerUser(phone: String, password: String, smsCode: String) {
        viewModelScope.launch {
            try {
                val res = authRepository.registerUser(phone, password, smsCode)
                _registerResponse.value = res
                // 如果发送成功（code==1），启动倒计时
                if (res.code == 1) {
                    startCountdown(60)
                    _toastMessage.postValue(EventUtil("用户注册成功，请返回登录"))
                }else{
                    _toastMessage.postValue(EventUtil("用户注册失败"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _toastMessage.postValue(EventUtil("网络错误"))
            }
        }
    }

    /**
     * 启动倒计时（单位秒）
     */
    private fun startCountdown(seconds: Int) {
        viewModelScope.launch {
            for (i in seconds downTo 0) {
                _countdown.value = i
                delay(1000)
            }
        }
    }

    /**
     * 发起登录请求
     */
    fun login(phone: String, password: String) {
        viewModelScope.launch {
            try {
                val res = authRepository.loginUser(phone, password)
                _loginResponse.value = res
                // 如果发送成功（code==1），启动倒计时
                if (res.code == 1) {
//                    _toastMessage.postValue(EventUtil("登陆成功"))
                }else{
                    _toastMessage.postValue(EventUtil("账号或密码错误"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _toastMessage.postValue(EventUtil("网络错误"))
            }
        }
    }

    /**
     * 调用忘记密码接口，重置密码
     */
    fun resetPassword(phone: String, smsCode: String, newPassword: String) {
        viewModelScope.launch {
            try {
                val res = authRepository.resetPassword(phone, smsCode, newPassword)
                _resetResponse.value = res
                // 如果发送成功（code==1），启动倒计时
                if (res.code == 1) {
                    startCountdown(60)
                    _toastMessage.postValue(EventUtil("密码重置成功,请返回登录"))
                }else{
                    _toastMessage.postValue(EventUtil("密码重置失败，该手机号未注册"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _toastMessage.postValue(EventUtil("网络错误"))
            }

        }
    }







}